// ALIBESteer.cpp file
#include <Arduino.h>
#include <ALIBEAM.h>

	ALIBEAM::ALIBEAM(){
		//
	}
	
	//public
	void ALIBEAM::begin(){
		initAndCaliberate();
	}

	void ALIBEAM::readValues(){
	  // read pulse from x- and y-axes:
	  int pulseX = pulseIn(ALIBE_X_AXIS_PIN,HIGH);  
	  int pulseY = pulseIn(ALIBE_Y_AXIS_PIN,HIGH);
	  // convert the pulse width into acceleration
	  // accelerationX and accelerationY are in milli-g's: 
	  // earth's gravity is 1000 milli-g's, or 1g.
	  xAcceleration = ((pulseX / 10) - 500) * 8;
	  yAcceleration = ((pulseY / 10) - 500) * 8;

	  // read temp
	  temp = analogRead(ALIBE_TEMPERATURE_PIN);
	  temp = map(temp,0,1024,32,199);
	}
	
	bool ALIBEAM::isMoving(){
	 int xDiff, yDiff;
	  int motionCounter = 0;

	  int loopCounter;
	  const int loopMax = 20;

	  bool bMoving=false;
	  
	  for(loopCounter = 1; loopCounter <loopMax; loopCounter++){
		readValues();
		xDiff = abs(xAcceleration - xInitial);
		yDiff = abs(yAcceleration - yInitial);
		if(xDiff >= ALIBE_X_THRESHOLD || yDiff >= ALIBE_Y_THRESHOLD){
		  motionCounter ++;  
		  if ( motionCounter >= ALIBE_MOTION_LEVEL_THRESHOLD ) {
			  xInitial = xAcceleration;
			  yInitial = yAcceleration;
			  bMoving=true;
			} else {
			  bMoving=false;
			} 
		  }
		}
		return bMoving;  
	}

	int ALIBEAM::temperature(){
		return temp ;
	}
	
	int ALIBEAM::xG(){
		return xAcceleration;
	}
	
	int ALIBEAM::yG(){
		return yAcceleration;
	}
	
	bool ALIBEAM::isDownwardSlope(){
		return (xAcceleration <= ALIBE_DOWNWARD_SLOPE_THRESHOLD);
	}
	bool ALIBEAM::isUpwardSlope(){
		return (xAcceleration >= ALIBE_UPWARD_SLOPE_THRESHOLD);
	}
	bool ALIBEAM::isTiltedLeft(){
		return (yAcceleration <= ALIBE_TILT_LEFT_THRESHOLD);
	}
	bool ALIBEAM::isTiltedRight(){
		return (yAcceleration >= ALIBE_TILT_RIGHT_THRESHOLD);
	}
	
	// private
	void ALIBEAM::initAndCaliberate(){
	  // initialize the pins connected to the accelerometer
	  // as inputs:
	  pinMode(ALIBE_X_AXIS_PIN, INPUT);
	  pinMode(ALIBE_Y_AXIS_PIN, INPUT);
	  
	  // read pulse from x- and y-axes:
	  int pulseX = pulseIn(ALIBE_X_AXIS_PIN,HIGH);  
	  int pulseY = pulseIn(ALIBE_Y_AXIS_PIN,HIGH);
	  // convert the pulse width into acceleration
	  // accelerationX and accelerationY are in milli-g's: 
	  // earth's gravity is 1000 milli-g's, or 1g.
	  xInitial = ((pulseX / 10) - 500) * 8;
	  yInitial = ((pulseY / 10) - 500) * 8;
	  readValues();
	}